package com.example.myword;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myword.util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    private EditText editTextEmail;
    private EditText editTextPassword;
    private CheckBox autoLoginCheckBox;
    private Button buttonLogin;
    private TextView textViewRegister;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        databaseHelper = new DatabaseHelper(this);

        if (UserPreferences.isAutoLogin(this)) {
            String token = UserPreferences.getUserToken(this);
            if (token != null|| verifyToken(token)) {
                attemptAutoLogin(token);
            } else {
                showLoginScreen();
            }
        } else {
            showLoginScreen();
        }
    }

    private void attemptAutoLogin(String token) {
        Map<String, Object> claims = JwtUtil.parseToken(token);
        // 跳转到主页面，并传递用户名作为 Extra 数据
        String email = (String) claims.get("email");
        String password = (String) claims.get("password");
//        String email = "123";
//        String password = "123";
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("username", email);
        intent.putExtra("userId", getUserIdFromDatabase(email, password));
        startActivity(intent);
        finish();
    }

    private boolean verifyToken(String token) {
        // 在此处进行实际的令牌验证逻辑
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
        }
        catch (Exception e){
            return false; // 解析失败了
        }
        return true; // 假设令牌有效
    }

    public void showLoginScreen(){
        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);
        buttonLogin = findViewById(R.id.buttonLogin);
        autoLoginCheckBox = findViewById(R.id.auto_login);
        textViewRegister = findViewById(R.id.textViewRegister);

        buttonLogin.setOnClickListener(v -> loginUser());
        textViewRegister.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, RegisterActivity.class)));
    }


    private void loginUser() {
        String email = editTextEmail.getText().toString();
        String password = editTextPassword.getText().toString();
        boolean autoLogin = autoLoginCheckBox.isChecked();


        if (email.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "Please enter email and password", Toast.LENGTH_SHORT).show();
            return;
        }

        if (databaseHelper.checkUser(email, password)) {
            // 登录成功
            // 生成JWT token的逻辑
            if(autoLogin){
                Map<String, Object> claims = new HashMap<>();
                claims.put("email", email);
                claims.put("password", password);
                String token = JwtUtil.genToken(claims);
                System.out.println("token="+token);
                // 这里进行实际的登录逻辑，假设登录成功并获得了token
                UserPreferences.saveUserToken(this, token);
                UserPreferences.setAutoLogin(this, autoLogin);
            }

            // 跳转到主页面，并传递用户名作为 Extra 数据
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("username", email);
            intent.putExtra("userId", getUserIdFromDatabase(email, password));
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "Login failed. Please check your credentials.", Toast.LENGTH_SHORT).show();
        }

    }

    // 示例方法：从数据库中获取用户ID
    private String getUserIdFromDatabase(String email, String password) {
        return databaseHelper.getUserIdFromDatabase(email, password);
    }

}

